<!DOCTYPE html>
<html>

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width,initial-scale=1,minimum-scale=1,maximum-scale=1,user-scalable=no" />
    <meta http-equiv="Pragma" content="no-cache" />
    <title>登录</title>
    <link rel="stylesheet" href="css/weui.min.css" />
    <link rel="stylesheet" href="fonts/iconfont.css" />
    <link rel="stylesheet" href="./fonts/qiheicon.css" />
    <link rel="stylesheet" href="css/style.css" />
    <link rel="stylesheet" href="css/index.css" />
    <script src="js/jquery-2.2.3.min.js"></script>
    <!-- <script src="js/weui.min.js"></script> -->
</head>


<body ontouchstart>

    <div class="weui-content">
        <div class="logo">
            <span class="iconqihe-logo" style="font-size:103px;">
                <span class="path1"></span><span class="path2"></span><span class="path3"></span><span class="path4"></span><span
                    class="path5"></span><span class="path6"></span><span class="path7"></span><span class="path8"></span><span
                    class="path9"></span><span class="path10"></span><span class="path11"></span><span class="path12"></span><span
                    class="path13"></span><span class="path14">
                </span>
            </span>

        </div>
        <form>
            <!-- 手机号 -->
            <div class="form-item">
                <span id="phone-icon" class="iconqihe-iphone"></span>
                <input type="number" pattern="[0-9]*" class="iphone phone-input" placeholder="请输入手机号">
            </div>
            <!-- 验证码 -->
            <div class="form-item">
                <input type="number" id="valicode" pattern="[0-9]*" class="verificationCode" placeholder="请输入验证码">
                <span class="iconqihe-lujing84" id="verificationCodeIcon"></span>
                <button class="getVerificationCode">
                    获取验证码
                </button>
            </div>
            <!-- 提交按钮 -->
            <div class="form-item">
                <button id="doLogin" class="submit" type="button" disabled="disabled">
                    绑定
                </button>
            </div>
            <!-- 加载提示gif -->
            <div id="Loding"></div>
        </form>
    </div>
</body>
<script src="./api.js"></script>
<script>
    window.onload = function () {
        let api = getApi()
        //点击获取验证码
        $('.getVerificationCode').on('click', function (event) {
            event.preventDefault()

            //验证码倒计时

            function waiteCode() {
                let times = 180
                let timer = null
                $('.getVerificationCode').text(times + 'S')
                $('.getVerificationCode').attr('disabled', true)
                $('.getVerificationCode').css('background', '#9F9F9F')
                $('.getVerificationCode').css('color', '#fff')
                $('.getVerificationCode').css('border', '2px solid #9F9F9F')
                $('.getVerificationCode').css('outline', '0px solid #9F9F9F')
                timer = setInterval(function () {
                    times--;
                    if (times <= 0) {
                        $('.getVerificationCode').text('获取验证码')
                        clearInterval(timer)
                        times = 180
                        $('.getVerificationCode').attr('disabled', false)//是否可点击   
                        $('.getVerificationCode').css('background', '#fff')
                        $('.getVerificationCode').css('color', '#F44831')
                        $('.getVerificationCode').css('border', '0.75px solid rgba(244,72,49,1)')

                        $('.submit').css('background', '#fff')
                        $('.submit').css('color', '#20A0FF')
                    } else {
                        $('.getVerificationCode').text(times + 'S')
                        $('.getVerificationCode').attr('disabled', true)
                        $('.getVerificationCode').css('background', '#9F9F9F')
                        $('.getVerificationCode').css('color', '#fff')
                        $('.getVerificationCode').css('border', '2px solid #9F9F9F')
                        $('.getVerificationCode').css('outline', '0px solid #9F9F9F')
                    }
                }, 1000)
            }

            waiteCode()

            //获取验证码
            let phoneNumber = $('.iphone').val()
            $.ajax({
                type: "get",
                url: `${api}/customer/bindWechat/message/${phoneNumber}`,
                datatype: "json",
                success: function (result) {
                    console.log(result)
                    if (result.state == false) {
                        alert(result.msg + ",请联系管理员！")
                        return
                    }
                }
            })
        })

        //验证码位数为4位时，绑定样式改变 & 可以点击
        $('.verificationCode').keyup(function () {
            let codeNum = $('.verificationCode').val().length
            if (codeNum > 0) {
                $('.submit').css('background', '#20A0FF')
                $('.submit').css('color', '#fff')
                $('#doLogin').attr('disabled', false)
            } else {
                $('.submit').css('background', '#fff')
                $('.submit').css('color', '#20A0FF')
                $('#doLogin').attr('disabled', false)
            }
        })

        $('.verificationCode').on('paste', function () {
            $('.submit').css('background', '#20A0FF')
            $('.submit').css('color', '#fff')
            $('#doLogin').attr('disabled', false)
        })


        //绑定提交
        $('#doLogin').on('click', function () {
            let phoneNumber = $('.iphone').val()
            let valicode = $('#valicode').val()
            let data = {
                phoneNumber: phoneNumber,
                valicode: valicode
            }

            //显示加载提示
            $('#Loding').html(
                ` <div id="loadingToast" style="opacity: 1; display: block;">
                    <div class="weui-mask_transparent"></div>
                    <div class="weui-toast">
                        <i class="weui-loading weui-icon_toast"></i>
                        <p class="weui-toast__content">数据加载中</p>
                    </div>
                </div>`
            )

            //获取用户信息
            let getUserInfo = new Promise(function (resolve, reject) {
                fetch(`${api}/customer/bindWechat/message`, {
                    method: "POST",
                    headers: {
                        'Content-type': 'application/json'
                    },
                    body: JSON.stringify(data)
                })
                    .then(res => res.json())
                    .then(data => {
                        resolve(data)
                    })
                    .catch(err => {
                        reject(err)
                    })
            })

            getUserInfo.then(function (data) {
                //若获取用户信息失败
                if (data.state == false) {

                    //关闭加载提示
                    $('#Loding').html('')

                    //验证码错误提示
                    alert(data.msg)

                    //验证码不正确时终止promise链
                    return new Promise(() => { });
                } else {

                    //拿到customerID 
                    let userInfo = JSON.parse(data.data)
                    console.log(userInfo)
                    let customerID = userInfo.data.customer.customerID

                    //将用户信息缓存到本地
                    localStorage.setItem('wxUserInfo', data.data)

                    //判断是否需要关联微信
                    if (userInfo.data.customer.weChatOpenID == null || userInfo.data.customer.weChatOpenID == '') {
                        location.href = api + "/outh?phoneNumber=" + phoneNumber;
                    }

                    //返回customerID  作为获取头像参数
                    return customerID
                }
            })
                .then(function (customerID) {
                    console.log(customerID, 'token', JSON.parse(localStorage.getItem('wxUserInfo')))
                    //获取用户头像
                    fetch(`${api}/getWxUserInfo?customerID=${customerID}`, {
                        method: "get",
                        headers: {
                            'Content-type': 'application/json',
                            "Authorization": JSON.parse(localStorage.getItem('wxUserInfo')).data.token
                        }
                    })
                        .then(res => res.json())
                        .then(data => {
                            let getWxImg = JSON.parse(data.data).headimgurl

                            //缓存头像
                            localStorage.setItem('getWxImg', getWxImg)

                            //关闭加载提示
                            $('#Loding').html('')

                            //跳转到首页
                            window.location.href = './home.html'
                            // window.location.replace('url')

                        })

                })
                .catch(function (ErrMsg) {
                    //获取数据失败时的处理
                    console.log(ErrMsg)
                })
        })
    }

</script>

</html>